package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.BusServiceItem;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.mapper.BusServiceItemMapper;
import cn.wolfcode.car.business.query.BusServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.IBusServiceItemService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class BusServiceItemServiceImpl implements IBusServiceItemService {

    @Autowired
    private BusServiceItemMapper busServiceItemMapper;
    @Autowired
    @Lazy
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;
    @Override
    public TablePageInfo<BusServiceItem> query(BusServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BusServiceItem>(busServiceItemMapper.selectForList(qo));
    }


    @Override
    public void save(BusServiceItem busServiceItem) {

        //从安全的考虑,前台传过来的对象不能直接操作数据库.
        BusServiceItem newObj = new BusServiceItem();
        newObj.setName(busServiceItem.getName());
        newObj.setOriginalPrice(busServiceItem.getOriginalPrice());
        newObj.setDiscountPrice(busServiceItem.getDiscountPrice());
        newObj.setCarPackage(busServiceItem.getCarPackage());
        newObj.setServiceCatalog(busServiceItem.getServiceCatalog());
        newObj.setInfo(busServiceItem.getInfo());
        newObj.setCreateTime(new Date());
        //套餐和非套餐
        if(BusServiceItem.CARPACKAGE_YES.equals(newObj.getCarPackage())){
            //套餐的默认审核状态----->初始化
            newObj.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        }else{
            //非套餐默认的审核状态--->无需审核
            newObj.setAuditStatus(BusServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        busServiceItemMapper.insert(newObj);
    }

    @Override
    public BusServiceItem get(Long id) {
        return busServiceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BusServiceItem busServiceItem) {
        BusServiceItem obj = this.get(busServiceItem.getId());
        if(BusServiceItem.SALESTATUS_ON.equals(obj.getSaleStatus())){
            throw new BusinessException("处于上架的服务单项不允许进行修改");
        }
        if(BusServiceItem.AUDITSTATUS_AUDITING.equals(obj.getAuditStatus())){
            throw new BusinessException("处于上审核中的服务单项不允许进行修改");
        }
        //如果是套餐,且处于审核通过,如果修改了,把审核状态修改成初始化
        if(BusServiceItem.AUDITSTATUS_APPROVED.equals(obj.getAuditStatus())){
            obj.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        }
        //把前台的属性设置到当前的对象中
        obj.setOriginalPrice(busServiceItem.getOriginalPrice());
        obj.setDiscountPrice(busServiceItem.getDiscountPrice());
        obj.setServiceCatalog(busServiceItem.getServiceCatalog());
        obj.setInfo(busServiceItem.getInfo());
        busServiceItemMapper.updateByPrimaryKey(obj);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            busServiceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BusServiceItem> list() {
        return busServiceItemMapper.selectAll();
    }

    @Override
    public void saleOn(Long id) {
        //根据id查询对象
        BusServiceItem busServiceItem = this.get(id);
        //处于下架状态
        if(BusServiceItem.SALESTATUS_OFF.equals(busServiceItem.getSaleStatus())){
            //非审核通过
            if(BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())&&//目前套餐
                    !BusServiceItem.AUDITSTATUS_APPROVED.equals(busServiceItem.getAuditStatus())){
                throw new BusinessException("套餐服务单项需要审核通过才能上架.");
            }
            //非套餐   ||  审核通过套餐  ===>把状态改成上架
            busServiceItem.setSaleStatus(BusServiceItem.SALESTATUS_ON);
            busServiceItemMapper.updateByPrimaryKey(busServiceItem);
        }
    }

    @Override
    public void saleOff(Long id) {
        BusServiceItem busServiceItem = this.get(id);
        if(BusServiceItem.SALESTATUS_ON.equals(busServiceItem.getSaleStatus())){
            busServiceItem.setSaleStatus(BusServiceItem.SALESTATUS_OFF);
            busServiceItemMapper.updateByPrimaryKey(busServiceItem);
        }
    }

    @Override
    @Transactional
    public void startAudit(Long id, Long shopOwnerId, Long financialId, String info) {
        //有什么样的限制条件
            //根据服务单项的id查询服务单项,判断状态是否处于初始化或者重新调整.
        BusServiceItem busServiceItem = this.get(id);
        if(BusServiceItem.AUDITSTATUS_INIT.equals(busServiceItem.getAuditStatus())||
                BusServiceItem.AUDITSTATUS_REPLY.equals(busServiceItem.getAuditStatus())
        ){
            //需要封装CarPackageAudit信息.
            CarPackageAudit audit = new CarPackageAudit();
            audit.setServiceItemId(busServiceItem.getId());
            audit.setServiceItemName(busServiceItem.getName());
            audit.setServiceItemPrice(busServiceItem.getDiscountPrice());
            audit.setServiceItemInfo(busServiceItem.getInfo());//套餐备注
            audit.setCreateTime(new Date());
            audit.setCreatorId(String.valueOf(ShiroUtils.getUserId()));
            audit.setInfo(info);//发起审核的备注信息
            carPackageAuditService.save(audit);
            //获取插入数据库中id的值
            String businessKey = String.valueOf(audit.getId());
            //如何找到对应流程定义,发起流程实例.
            //通过CarPackageAudit.AUDIT_TYPE去bpmnInfo表中查询记录
            //如果有多个,按照部署时间取最近部署的那个.
            BpmnInfo bpmnInfo = bpmnInfoService.getByBpmnType(CarPackageAudit.AUDIT_TYPE);
            //如果查询返回null,说明没有上传流程定义.
            if(bpmnInfo==null){
                throw new BusinessException("缺少流程定义,请联系管理员");
            }
            //流程定义的Key
            String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();
            //发起流程的时候需要携带审核参数到流程中.
            //需要定义Map集合,存储店长id,财务id,折扣金额
            Map<String,Object> params = new HashMap<>();
            params.put("shopOwnerId",shopOwnerId);
            params.put("financeId",financialId);
            params.put("disCountPrice",busServiceItem.getDiscountPrice().longValue());
            //启动流程实例,业务key和流程变量在启动的时候一并传入.
            ProcessInstance instance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, params);
            //服务单项的的状态怎么改变呢.改成审核中.
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_AUDITING);
            busServiceItemMapper.updateByPrimaryKey(busServiceItem);
            //CarPackageAudit信息需要设置instanceId???
            audit.setInstanceId(instance.getId());
            carPackageAuditService.update(audit);
        }else{
            throw new BusinessException("非法操作");
        }

    }

    @Override
    public void changeStatus(Long serviceItemId, Integer status) {
        busServiceItemMapper.changeStatus(serviceItemId,status);
    }
}
